#!/usr/bin/env php
<?php
//declare(ticks = 1);
$is_show_errors = false;
foreach ($argv as $item) {
	if (strpos($item, "debug") !== false) {
		$is_show_errors = true;
		ini_set("display_errors", "On");
		error_reporting(E_ALL);
	}
}

//初始化一些系统常量
define("WINDOWS", "windows");
define("LINUX", "linux");
//根目录
define("HOME", __DIR__);

//初始化日志目录
if (!is_dir(__DIR__."/logs")) {
    mkdir(__DIR__."/logs");
}

include __DIR__."/src/helpers.php";

//初始化命令行参数
$str_argv = '';
for ($i = 1; $i < $argc; $i++) {
    $str_argv .= ' '.$argv[$i];
}

$file_name = str_replace(__DIR__, "", __FILE__);
$file_name = trim($file_name, "/");
$file_name = trim($file_name, "\\");

$command_line = 'php '.$file_name.' '.$str_argv;
define("WING_COMMAND_LINE", $command_line);

if (is_env(WINDOWS) && !file_exists(__DIR__."/composer.json")) {
    copy(__DIR__."/composer.json.win", __DIR__."/composer.json");
} else if(!file_exists(__DIR__."/composer.json")) {
    copy(__DIR__."/composer.json.linux", __DIR__."/composer.json");
}

if (!file_exists(__DIR__.'/vendor/autoload.php')) {
    echo "正在尝试安装依赖-composer install", PHP_EOL;
    exec("composer install");
//    echo PHP_EOL, "请重新执行：", WING_COMMAND_LINE, PHP_EOL;
//    exit;
}

if (!function_exists("socket_create")) {
    echo "请安装php_sockets扩展", PHP_EOL;
    exit;
}

require __DIR__.'/vendor/autoload.php';
require __DIR__.'/src/windows.php';

use Symfony\Component\Console\Application;

//定义时间区
if (!date_default_timezone_get() || !ini_get("date.timezone")) {
    date_default_timezone_set("PRC");
}

//初始化开发模式
$debug = false;
foreach ($argv as $item) {
    if (strpos($item, "debug") !== false) {
		$debug = true;
    }

    if (strpos($item, "restart") !== false) {
        $winfo  = \Wing\Library\Worker::getWorkerProcessInfo();
        $debug  = $winfo["debug"];
    }
}
define("WING_DEBUG", $debug);

if (WING_DEBUG && !$is_show_errors) {
	ini_set("display_errors", "On");
	error_reporting(E_ALL);
}

try {

    $application = new Application("wing-binlog");
    $application->setCatchExceptions(true);

    $commands = [
        \Wing\Command\ServerStart::class,
        \Wing\Command\ServerStop::class,
        \Wing\Command\ServerVersion::class,
        \Wing\Command\ServerStatus::class,
        \Wing\Command\Help::class,
        \Wing\Command\ServerRestart::class
    ];
    foreach ($commands as $command) {
        $application->add(new $command);
    }

    $application->run();
} catch (\Exception $e) {
    var_dump($e);
}